<?php

class Auth {
	const SESSION_KEY = 'Auth.user';
	
	public static function user() {
		if (self::logged_in()) {
			return Session::read(self::SESSION_KEY);
		}
	}
	
	public static function logged_in() {
		return !is_null(Session::read(self::SESSION_KEY)) ? true : false;
	}
	
	public static function login($username = null, $password = null) {
		$username = trim(strip_tags($username));
		$password = trim(strip_tags($password));
		if (!self::check($username, $password)) {
			return false;
		} else {
			Session::regenerate();
			Session::write(self::SESSION_KEY, $username);
			return true;
		}
		return false;	
	}
	
	public static function logout() {
		Session::delete(self::SESSION_KEY);
		Session::destroy();
	}

	private function check($username = null, $password = null) {
		$result = Mssql::fetch('SELECT COUNT(1) AS total FROM MEMB_INFO WHERE memb___id = :username[string] AND memb__pwd = :password[string]', array('username' => $username, 'password' => $password));
		return $result->total == 1;
	}
}

?>